//
//  DoorSystemUPdateViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/3/13.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorSystemUPdateViewController.h"

@interface DoorSystemUPdateViewController ()<UITableViewDelegate,UITableViewDataSource,MyCameraDelegate>{
    MyCamera *camera;
    BOOL isRecvInfo;
    
    NSInteger upgradeType;
    NSInteger upgradeStatus;
    NSInteger newFlag;
    NSInteger newValue;

}
/** tableview **/
@property(nonatomic,strong) UITableView *tableView;

/** Btn **/
@property(nonatomic,strong) UIButton *cleanbtn;

@property(nonatomic,strong) NSArray *titleArray;

/** <#Description#> **/
@property(nonatomic,strong) NSString *currentSYS;

/** <#Description#> **/
@property(nonatomic,strong) NSString *latestSYS;

@end

@implementation DoorSystemUPdateViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];

    camera = [AppDelegate globalDelegate].cameraModel;
    [AppDelegate globalDelegate].cameraModel.delegate2 = self;
    
}
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    camera.delegate2 = nil;
    [SVProgressHUD dismiss];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationStyle];
    self.titleArray = @[@"摄像机固件版本",@"摄像机最新固件版本"];
    newValue = -1;
    
    isRecvInfo = false;
    newFlag = NEW_FLAG_NONE;
    upgradeType = NEW_FLAG_INIT;
    upgradeStatus = UPGRADE_INIT;
    
    [SVProgressHUD showWithStatus:@"获取信息中..."];
    // get upgrade info
    SMsgAVIoctrlSetUpgradeOnlineReq *structUpgradeOnline = malloc(sizeof(SMsgAVIoctrlSetUpgradeOnlineReq));
    memset(structUpgradeOnline, 0, sizeof(SMsgAVIoctrlSetUpgradeOnlineReq));
    structUpgradeOnline->type = UPGRADE_ONLINE_TYPE_CHECK;
    
    [[AppDelegate globalDelegate].cameraModel sendIOCtrlToChannel:0
                                                             Type:IOTYPE_USER_IPCAM_SET_UPGRDEONLIN_REQ
                                                             Data:(char *)structUpgradeOnline
                                                         DataSize:sizeof(SMsgAVIoctrlSetUpgradeOnlineReq)];
    free(structUpgradeOnline);

}
- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"固件升级" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
}

#pragma mark - tableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 54.f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}

#pragma mark - tableView Delegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        [cell.textLabel setFont:[UIFont systemFontOfSize:15.f]];
        [cell.detailTextLabel setFont:[UIFont systemFontOfSize:15.f]];
    }
    
    cell.textLabel.text = self.titleArray[indexPath.row];
    

    if (indexPath.row == 0) {
        
        if (isRecvInfo == YES) {
            [SVProgressHUD dismiss];
            cell.detailTextLabel.text = [self.currentSYS copy];

        } else {
            cell.detailTextLabel.text = @"";

        }

        
    }else if(indexPath.row == 1){
        
        if (isRecvInfo == YES) {
            cell.detailTextLabel.text =  [self.latestSYS copy];

            } else {
                cell.detailTextLabel.text = @"";

            }

            
       
    }
    
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}

#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    if (camera_ == camera) {
        NSLog(@"type:%ld", (long)type);
        if (type == IOTYPE_USER_IPCAM_SET_UPGRADEONLIN_RESP) {
            
            SMsgAVIoctrlUpgradeOnlineResp *s = (SMsgAVIoctrlUpgradeOnlineResp*)data;
            
            if (UPGRADE_ONLINE_TYPE_CHECK == s->type) {
                if (NEW_FLAG_NONE == s->result) {
                    NSLog(@"no new");
                } else if (NEW_FLAG_SYS == s->result) {
                    NSLog(@"new sys");
                } else if (NEW_FLAG_UI == s->result) {
                    NSLog(@"new ui");
                } else if (NEW_FLAG_SYS_UI == s->result) {
                    NSLog(@"new sys&ui");
                } else {
                    NSLog(@"result:%d", s->result);
                }
                newFlag = s->result;
                NSLog(@" current_ui_version:%s", s->current_ui_version);
                NSLog(@"current_sys_version:%s", s->current_sys_version);
                NSLog(@"  latest_ui_version:%s", s->latest_ui_version);
                NSLog(@" latest_sys_version:%s", s->latest_sys_version);
                
                self.currentSYS = [[NSString alloc] initWithCString:s->current_sys_version encoding:NSUTF8StringEncoding];
                self.latestSYS = [[NSString alloc] initWithCString:s->latest_sys_version encoding:NSUTF8StringEncoding];
                
                isRecvInfo = true;
            } else {
                NSLog(@"type:%d result:%d", s->type, s->result);
                NSLog(@" current_ui_version:%s", s->current_ui_version);
                NSLog(@"current_sys_version:%s", s->current_sys_version);
                NSLog(@"  latest_ui_version:%s", s->latest_ui_version);
                NSLog(@" latest_sys_version:%s", s->latest_sys_version);
                if (0 == s->result) {
                    upgradeStatus = UPGRADE_RUNNING;
                    NSLog(@"running");
//                    [SVProgressHUD showWithStatus:@"请不要将设备断电,请等待..."];
                    // show reboot dialog
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"Firmware upgrade takes %@ minutes", @""), (s->type == UPGRADE_ONLINE_TYPE_SYS)?@"5~8":@"3~5"] message:[NSString stringWithFormat:NSLocalizedString(@"Don't shutdown device's power.Please waiting ...", @"")] delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil];
                    [alert setAlertViewStyle:UIAlertViewStyleDefault];
                    [alert show];
                } else {
                    upgradeStatus = UPGRADE_FAIL;
                    NSLog(@"fail");
                    // show reboot dialog
                    [SVProgressHUD showErrorWithStatus:@"升级失败"];
//                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Warning", @"") message:[NSString stringWithFormat:NSLocalizedString(@"Firmware Upgrade Failed", @"")] delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil];
//                    [alert setAlertViewStyle:UIAlertViewStyleDefault];
//                    [alert show];
                }
            }
            
            [self.tableView reloadData];
        }
    }
    
}


- (void)cleanEvent{
    
    
    if (isRecvInfo) {
        if (NEW_FLAG_SYS == newFlag || NEW_FLAG_SYS_UI == newFlag) {
            upgradeType = NEW_FLAG_SYS;
            // show reboot dialog
        
        } else {
            upgradeType = NEW_FLAG_NONE;
            NSLog(@"sys no new  newFlag:%ld", (long)newFlag);
            // show reboot dialog
            return [SVProgressHUD showInfoWithStatus:@"当前为最新版本!"];
        }
        
    } else {
        NSLog(@"upgradeSYS isRecvInfo==false");
    }

    
    
    
    if (camera != nil && camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
        
        if (upgradeType == NEW_FLAG_SYS) {
            // upgrade sys
            SMsgAVIoctrlSetUpgradeOnlineReq *structUpgradeOnline = malloc(sizeof(SMsgAVIoctrlSetUpgradeOnlineReq));
            memset(structUpgradeOnline, 0, sizeof(SMsgAVIoctrlSetUpgradeOnlineReq));
            structUpgradeOnline->type = UPGRADE_ONLINE_TYPE_SYS;
            
            [camera sendIOCtrlToChannel:0
                                   Type:IOTYPE_USER_IPCAM_SET_UPGRDEONLIN_REQ
                                   Data:(char *)structUpgradeOnline
                               DataSize:sizeof(SMsgAVIoctrlSetUpgradeOnlineReq)];
            free(structUpgradeOnline);
        } else if(upgradeType == NEW_FLAG_UI) {
            // upgrade ui
            SMsgAVIoctrlSetUpgradeOnlineReq *structUpgradeOnline = malloc(sizeof(SMsgAVIoctrlSetUpgradeOnlineReq));
            memset(structUpgradeOnline, 0, sizeof(SMsgAVIoctrlSetUpgradeOnlineReq));
            structUpgradeOnline->type = UPGRADE_ONLINE_TYPE_UI;
            
            [camera sendIOCtrlToChannel:0
                                   Type:IOTYPE_USER_IPCAM_SET_UPGRDEONLIN_REQ
                                   Data:(char *)structUpgradeOnline
                               DataSize:sizeof(SMsgAVIoctrlSetUpgradeOnlineReq)];
            free(structUpgradeOnline);
        } else if(upgradeType == NEW_FLAG_NONE) {
            
        } else {
        }
        
    } else {
        
        [SVProgressHUD showErrorWithStatus:@"设备离线"];
    }
    NSLog(@"upgradeStatus:%ld", (long)upgradeStatus);
    if (upgradeStatus == UPGRADE_RUNNING ||
        upgradeStatus == UPGRADE_FAIL) {
        upgradeStatus = UPGRADE_INIT;
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        
    }

    
}
- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(superView);
        
    }];
    [self.cleanbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.centerY.mas_equalTo(superView.mas_centerY).mas_offset(-80);
        
    }];
}

- (UIButton *)cleanbtn{
    
    if (!_cleanbtn) {
        __weak UIView *superView = self.view;
        
        _cleanbtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [superView addSubview:_cleanbtn];
        
        [_cleanbtn setBackgroundImage:[UIImage imageNamed:@"login_button_nor"] forState:UIControlStateNormal];
        [_cleanbtn setBackgroundImage:[UIImage imageNamed:@"login_button_sel"] forState:UIControlStateHighlighted];
        [_cleanbtn addTarget:self action:@selector(cleanEvent) forControlEvents:UIControlEventTouchUpInside];
        [_cleanbtn setTitle:@"升级" forState:UIControlStateNormal];
    }
    return _cleanbtn;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        _tableView.scrollEnabled = NO;
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        //        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    
    return _tableView;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
